package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.TaskDetails2Activity;
import com.mingtu.jgspatrol.adapter.Task2Adapter;
import com.mingtu.jgspatrol.bean.TaskTemBean;
import com.mingtu.jgspatrol.databinding.FragmentTask2Binding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Task2Fragment extends BaseBindingFragment<FragmentTask2Binding> implements LazyFragmentPagerAdapter.Laziable {

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private Task2Adapter task2Adapter;
    private List<TaskTemBean.PageBean.ListBean> DataBean = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task2;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, ItemDecorationSpaces));

        task2Adapter = new Task2Adapter(context);
        if (isOpenLoadAnimation) {
            task2Adapter.isFirstOnly(isFirstOnly);
            task2Adapter.openLoadAnimation(animationType);
        }
        task2Adapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(task2Adapter);
        task2Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                TaskTemBean.PageBean.ListBean listBean = task2Adapter.getData().get(i);
                String taskId = listBean.getId() + "";

                if (!StringUtils.isEmpty(taskId)) {
                    Intent intent = new Intent(getActivity(), TaskDetails2Activity.class);
                    intent.putExtra("taskId", taskId);
                    startActivityForResult(intent, 100);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getTaskList(1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == 200) {
                getTaskList(1);
            }
        }
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getTaskList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
                    getTaskList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 临时任务列表
     */
    private void getTaskList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_TASK_LIST_TEM)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            TaskTemBean taskTemBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                taskTemBean = new TaskTemBean();
                                taskTemBean = gson.fromJson(result, TaskTemBean.class);
                                List<TaskTemBean.PageBean.ListBean> dataBeans = taskTemBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        if (currentPage == 1) {
                                            task2Adapter.replaceData(dataBeans);
                                        } else {
                                            task2Adapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

}